package com.itgacl.magic4j.libcommon.component.ws;

import com.alibaba.fastjson.JSON;
import com.itgacl.magic4j.libcommon.component.ws.cluster.bean.WebsocketMsg;
import com.itgacl.magic4j.libcommon.component.ws.cluster.listener.WebsocketMsgListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

@Slf4j
@ConditionalOnProperty(prefix = "ws", value = "enable", havingValue = "true")
@Component
public class WsMsgListener implements WebsocketMsgListener {

    @Autowired
    private WsService wsService;

    @Override
    public void receiveMessage(String websocketJsonMsg) {
        WebsocketMsg websocketMsg = JSON.parseObject(websocketJsonMsg,WebsocketMsg.class);
        log.debug("WsMsgListener websocketMsg:{}",websocketMsg);
        WebSocketSession webSocketSession = WsSessionManager.get(websocketMsg.getReceiverId());
        if(webSocketSession!=null){
            try {
                //发送消息到客户端
                wsService.sendMsg(webSocketSession, websocketMsg.getContent());
            }catch (Exception e){
                log.error(e.getMessage(),e);
            }
        }
    }
}
